package framework
{
	import mx.resources.ResourceManager;
	import mx.utils.ObjectUtil;
	
	import utils.ObjectUtil;
	import utils.XMLUtil;

	public class LangMgr
	{
		/**
		 * 语言包缓存
		 */
		public static var langPkgCaches:Object = {};
		
		/**
		 * 已加载语言包
		 */
		private static var loadedLangPkg:Array = [];
		
		/**
		 * 加载语言包
		 */
		public static function loadLangPkg(p_pkgName:String):void
		{
			if(loadedLangPkg.indexOf(p_pkgName) >= 0)
				return;
			XMLUtil.loadXML("flex/language/" + AppGlobal.currentLang + "/" + p_pkgName + ".xml", loadLangResultHandler);
			
			//加载完成后回调函数
			function loadLangResultHandler(p_xml:XML):void
			{
				//添加到已加载列表
				loadedLangPkg.push(p_pkgName);
				var langPkg:Object = XMLUtil.XMLToObject(p_xml);
				//合并语言包
				langPkgCaches = utils.ObjectUtil.mergeObject(langPkgCaches, langPkg);
				//更新视图
				ResourceManager.getInstance().update();
			}
		}
		
		/**
		 * 根据LOCALE KEY获取相关国际化信息字符串(以|作为拼接符，以.作为层次分割符)
		 */
		public static function getResourceByLocaleKey(p_localeKey:String):String
		{
			if(!p_localeKey)return "";
			var arr:Array = p_localeKey.split("|");
			var str:String = "";
			for(var i:int = 0;i < arr.length;i++){
				str += getResource(String(arr[i]));
			}
			return str;
		}
		
		/**
		 * 获取相关资源
		 */
		private static function getResource(p_localeKey:String):String
		{
			//如果字符串曾经，则从缓存中获取，避免每次都循环
			if(LocaleCaches.stringCaches[p_localeKey])
				return LocaleCaches.stringCaches[p_localeKey];
			var arr:Array = p_localeKey.split(".");
			var obj:Object = mx.utils.ObjectUtil.copy(langPkgCaches);
			for(var i:int = 0;i < arr.length;i++){
				obj = obj[arr[i]];
				if(!obj)break;
			}
			if(obj){
				LocaleCaches.stringCaches[p_localeKey] = String(obj);
				return String(obj);
			}else
				return p_localeKey;
		}
	}
}